package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.MashStep;
import Models.MashSchedule;

public class MashSchedulePresenter extends AbstractPresenter<MashSchedule> {
	final String SINGLEITEM = "mashSchedule";
	final String MULTIITEM = "mashSchedules";
	
	public ArrayList<MashSchedule> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public MashSchedule tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public MashSchedule tryJSONParseNoHeader(String input){
		try{
			JSONObject jsonHop = new JSONObject(input);
			MashSchedule item = createItemFromJSONObject(jsonHop);
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public MashSchedule createItemFromJSONObject(JSONObject jsonObject){
		MashSchedule item = new MashSchedule();
		try{
			item.setId(jsonObject.getInt("scheduleID"));
			item.setDescription(jsonObject.getString("description"));
			
			//Set MashStep Collection
			ArrayList<MashStep> mashSteps = new ArrayList<MashStep>();
			if(!jsonObject.isNull("mashStepCollection")){
				Object itm = jsonObject.get("mashStepCollection");
				MashStepPresenter presenter = new MashStepPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						mashSteps.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					mashSteps.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setMashSteps(mashSteps);
			}
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(MashSchedule item){
		try{
			JSONObject json = new JSONObject();
			json.put("scheduleID", item.getId());
			json.put("description", item.getDescription());
			
			//Create MashStep Collection
			if(item.getMashSteps()!=null){
				MashStepPresenter presenter = new MashStepPresenter();
				if(item.getMashSteps().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getMashSteps().size(); i++){
						jsonArray.put(presenter.createJSON(item.getMashSteps().get(i)));
					}
					json.put("mashStepCollection", jsonArray);
				}
			}
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public MashSchedule getEmptyEntity(){
		MashSchedule entity = new MashSchedule();
		return entity;
	}
}
